<?php

use App\Exceptions\ApiException;
use App\Models\Api;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\App;
use GatewayWorker\Lib\Gateway;

if (!function_exists('app_path')) {
    /**
     * Get the path to the application folder.
     *
     * @param  string $path
     * @return string
     */
    function app_path($path = '')
        {
        return app('path') . ($path ? DIRECTORY_SEPARATOR . $path : $path);
        }
    }

if (!function_exists('auditSave')) {
    /**
     * Get the path to the application folder.
     *
     * @param  string $path
     * @return mixed
     */
    function auditSave(&$model, $isAssign = true, $autosave = true, $status_id = null)
        {
        if ($isAssign) {
            $model['auditor_id'] = auth()->user()?->employee_id;
            $model['audited_at'] = date("Y-m-d H:i:s");
            $model['status_id']  = $status_id ?? 1;
            }
        else {
            $model['auditor_id'] = 0;
            $model['audited_at'] = null;
            $model['status_id']  = $status_id ?? 0;
            }
        if ($autosave)
            $model->save();
        return $model;
        }
    }
if (!function_exists('fauditSave')) {
    /**
     * Get the path to the application folder.
     *
     * @param  string $path
     * @return mixed
     */
    function fauditSave(&$model, $isAssign = true, $autosave = true, $status_id = null)
        {
        if ($isAssign) {
            $model['fauditor_id'] = auth()->user()?->employee_id;
            $model['faudited_at'] = date("Y-m-d H:i:s");
            $model['status_id']   = $status_id ?? 2;
            }
        else {
            $model['fauditor_id'] = 0;
            $model['faudited_at'] = null;
            $model['status_id']   = $status_id ?? 1;
            }
        if ($autosave)
            $model->save();
        return $model;
        }
    }
if (!function_exists('enable')) {
    /**
     * Get the path to the application folder.
     *
     * @param  string $path
     * @return string
     */
    function enable(&$model, $isAssign = true, $autosave = true)
        {
        if ($isAssign && $model->status_id == 0) {
            fail("已启用，无法再次启用");
            }
        if (!$isAssign && $model->status_id == -1) {
            fail("已禁用，无法再次禁用");
            }
        return auditSave($model, $isAssign, $autosave, $isAssign ? 0 : -1);
        }
    }
if (!function_exists("wsSend")) {

    function wsSend($event, $data = '', $client_id = 0, $success = true)
        {
        if ($client_id == 0) {
            $client_ids = app("token")->sockets->pluck("socket_fd");
            }
        else {
            $client_ids[] = $client_id;
            }
        $data = ['success' => $success, 'event' => $event, 'data' => $data];
        foreach ($client_ids as $client_id) {
            Gateway::sendToClient($client_id, json_encode($data));
            }
        }
    }
if (!function_exists("wsFail")) {

    function wsFail($data = '', $client_id = 0)
        {
        wsSend("", $data, $client_id, false);
        }
    }

if (!function_exists("fail")) {
    function fail($msg, $code = 500, $data = "")
        {
        throw new ApiException($msg, $code, $data);
        }
    }
if (!function_exists('stringToArray')) {
    function stringToArray($param)
        {
        if (is_array($param))
            return $param;
        else
            return [$param];
        }
    }
if (!function_exists('getArrayableItems')) {
    function getArrayableItems($items)
        {
        $res = [];
        if (is_array($items)) {
            $res = $items;
            }
        elseif ($items instanceof Illuminate\Support\Enumerable) {
            $res = $items->all();
            }
        elseif ($items instanceof Illuminate\Contracts\Support\Arrayable) {
            $res = $items->toArray();
            }
        elseif ($items instanceof Illuminate\Contracts\Support\Jsonable) {
            $res = json_decode($items->toJson(), true);
            }
        elseif ($items instanceof JsonSerializable) {
            $res = (array) $items->jsonSerialize();
            }
        elseif ($items instanceof Traversable) {
            $res = iterator_to_array($items);
            }
        else {
            return false;
            }

        return $res;
        }
    }
if (!function_exists('uuid')) {
    /**
     * 生成UUID 单机使用
     */
    function uuid()
        {
        $charid = md5(uniqid(mt_rand(), true));
        $hyphen = chr(45);
        return substr($charid, 0, 8) . $hyphen . substr($charid, 8, 4) . $hyphen . substr($charid, 12, 4) . $hyphen . substr($charid, 16, 4) . $hyphen . substr($charid, 20, 12);
        }
    }
// function validator
// $val = app('validator')->make([$file], [
//     'file' => "required|mimes:{$this->allowExts}|max:{$this->maxsize}",
//     []
// ]);

if (!function_exists('isEmpty')) {
    /**
     * 判断是否为空,主要区分空字符串
     */
    function isEmpty($string)
        {
        return ($string ?? '') === '';
        }
    }
if (!function_exists('isNotEmpty')) {
    /**
     * 判断是否不为空
     */
    function isNotEmpty($string)
        {
        return ($string ?? '') !== '';
        }
    }
if (!function_exists('config_path')) {
    /**
     * Get the configuration path.
     *
     * @param  string $path
     * @return string
     */
    function config_path($path = '')
        {
        return app()->basePath() . '/config' . ($path ? '/' . $path : $path);
        }
    }
if (!function_exists("treeListCallBack")) {
    /**
     * 树形菜单 循环 执行回调
     * @param $child_tree 树形菜单，子菜单必须是children
     */
    function treeListCallBack($child_tree, callable $callback)
        {


        if ($child_tree instanceof Collection) {
            foreach ($child_tree as $v) {
                treeListCallBack($v, $callback);
                }
            }
        else {

            if (!$child_tree->children->isEmpty())
                foreach ($child_tree->children as $child)
                    treeListCallBack($child, $callback);
            return $callback($child_tree);
            }
        }
    }

if (!function_exists("readImageRgb")) {
    function readImageRgb($image)
        {
        $rTotal = $gTotal = $bTotal = $total = 0;

        $image_info = getimagesize($image);

        switch ($image_info['mime']) {
            case 'image/png':
                // 处理 PNG 文件
                $i = imagecreatefrompng($image);
                break;
            case 'image/jpeg':
                // 处理 JPEG 文件
                $i = imagecreatefromjpeg($image);
                break;
            case 'image/gif':
                // 处理 GIF 文件
                $i = imagecreatefromgif($image);
                break;
            default:
                // 其他类型的文件
                fail('Unsupported image format: ' . $image_info['mime']);
            }
        // $i = imagecreatefromjpeg($image);
        // if (!$i)
        //     $i = imagecreatefrompng($image);
        // if ($i == false)
        //     return false;
        for ($x = 0; $x < imagesx($i); $x++) {
            for ($y = 0; $y < imagesy($i); $y++) {
                $rgb    = imagecolorat($i, $x, $y);
                $r      = ($rgb >> 16) & 0xFF;
                $g      = ($rgb >> 8) & 0xFF;
                $b      = $rgb & 0xFF;
                $rTotal += $r;
                $gTotal += $g;
                $bTotal += $b;
                $total++;
                }
            }
        $rAverage = "00" . dechex(round($rTotal / $total));
        $gAverage = "00" . dechex(round($gTotal / $total));
        $bAverage = "00" . dechex(round($bTotal / $total));
        return
            substr($rAverage, strlen($rAverage) - 2) .
            substr($gAverage, strlen($gAverage) - 2) .
            substr($bAverage, strlen($bAverage) - 2);
        }
    }
function getRouter($name = null)
    {
    $request = request();
    if ($name != null) {
        $r = $request->route($name);
        if ($name != 'action')
            $r = ucfirst($r);
        return $r;
        }
    $res['model']      = ucfirst($request->route("model"));
    $res['controller'] = ucfirst($request->route("controller"));
    $res['action']     = $request->route("action");
    return $res;
    }
function getApi()
    {
    return Api::where(getRouter())->first();
    }
function getEvent()
    {
    $router = getRouter();
    return "App\\Events\\{$router['model']}\\{$router['controller']}\\{$router['action']}Event";
    }
function getController()
    {
    $router = getRouter();
    return "App\\Http\\Controllers\\{$router['model']}\\{$router['controller']}Controller";
    }
function getValidate()
    {
    $router = getRouter();
    return "App\Http\\Validates\\{$router['model']}\\{$router['controller']}Validate";
    }
function getImport()
    {
    $router = getRouter();
    return "App\Http\\Imports\\{$router['model']}\\{$router['controller']}Import";
    }
function callController($M = '', $C = '', $A = '')
    {

    $class = App::make("App\Http\Controllers\\{$M}\\{$C}Controller");
    if (method_exists($class, $A)) {
        return App::call([$class, $A]);
        }
    return App::call([$class, 'callend']);
    }
function makeRepository($modelName)
    {
    return App::make("App\Repositories\\{$modelName}Repository");
    }
function arrayToXml($list, $parentKey = '')
    {
    $parentKey = $parentKey == '' ? '' : $parentKey . ".";
    $xml       = '';
    foreach ($list as $k => $v) {
        if (is_array($v)) {
            $xml .= arrayToXml($v, $parentKey == "." ? $k : $parentKey . $k);
            }
        else {
            $xml .= "<{$parentKey}{$k}>" . ($v ?? "") . "</{$parentKey}{$k}>";
            }
        }
    return $xml;
    }

function arrayToGrid($list, &$xml, $parentKey = '')
    {
    $parentKey = $parentKey == '' ? '' : $parentKey . "_";
    foreach ($list as $k => $v) {
        if (is_array($v)) {
            arrayToGrid($v, $xml, $parentKey == "_" ? $k : $parentKey . $k);
            }
        else {
            $xml["{$parentKey}{$k}"] = $v;
            }
        }
    return $xml;
    }
function createGrid($list)
    {
    $xml = [];
    foreach ($list as $k => $v) {
        if (is_array($v)) {
            arrayToGrid($v, $xml, $k);
            }
        else {
            $xml[$k] = $v;
            }
        }
    return $xml;
    }

function createReport($details = [])
    {
    $report = "<xml>";
    foreach ($details as $v) {
        $report .= "<row>";
        $report .= arrayToXml($v);
        $report .= "</row>";
        }
    $report .= "</xml>";
    return $report;
    }

function findAllChildIdArray($needarray, $parentids, $parentidstr = "parent_id", $idstr = "id")
    {
    $arrayfun = [];
    foreach ($parentids as $k => $v)
        $arrayfun = array_merge($arrayfun, findAllChildIdunset($needarray, $v, $parentidstr, $idstr));
    return $arrayfun;
    }

function findAllChildIdunset(&$needarray, $parentid, $parentidstr = "parent_id", $idstr = "id")
    {
    $arrayfun[] = $parentid;
    // dump($needarray);
    foreach ($needarray as $key => $val) {
        if ($val[$parentidstr] == $parentid) {
            unset($needarray[$key]);
            $arrayfun = array_merge($arrayfun, findAllChildIdunset($needarray, $val[$idstr], $parentidstr, $idstr));
            }
        }
    return $arrayfun;
    }


if (!function_exists('config_path')) {
    /**
     * Summary of config_path
     * @param string $path
     * @return string
     * @author sunkaiyuan
     */
    function config_path($path = '')
        {
        return app()->basePath() . '/config' . ($path ? '/' . $path : $path);
        }
    }



function sql()
    {
    $queryLog = DB::getQueryLog();

    // 使用集合操作来格式化查询日志
    return collect($queryLog)->map(function ($query)
        {
        // 获取查询的SQL和绑定
        $sql      = $query['query'];
        $bindings = $query['bindings'];

        // 替换SQL中的绑定
        foreach ($bindings as $binding) {
            $value = is_numeric($binding) ? $binding : "'" . $binding . "'";
            $sql   = preg_replace('/\?/', $value, $sql, 1);
            }

        // 返回格式化后的查询和执行时间
        return ['query' => $sql, 'time' => $query['time']];
        })->all();
    }